package com.topc.auth.api;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.topc.base.api.CommonResult;
import com.topc.base.constant.RedisConstant;
import com.topc.base.utils.TimeUtils;
import com.topc.core.sevice.RedisService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;


import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.Map;

@Api(value = "OAuth接口")
@RestController
@RequestMapping("/oauth")
@Slf4j
public class AuthController implements InitializingBean {

    //令牌请求的端点
    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Autowired
    private RedisService redisService;

    // 这里是接收参数和返回参数的地方
    @GetMapping(value = "/token")
    public CommonResult<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam
    Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        System.out.println("success");
        String userJson = parameters.get("username");
        if (ObjectUtil.isEmpty(userJson)) return CommonResult.validateFailed("参数传递不全");
        JSONObject jsonObject = JSONObject.parseObject(userJson);
        String number = jsonObject.getString("number");
        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        String oauthEndpoint = jsonObject.getString("oauthEndpoint");
        if (ObjectUtil.equal(oauthEndpoint,"admin")){
             redisService.hSet(RedisConstant.ADMIN_ONLINE_NUMBER,"admin_"+number,TimeUtils.timeFormat(LocalDateTime.now()));
             redisService.lrPush(RedisConstant.ADMIN_PROJECT_DYNAMIC_EVALUATION,
                    number+":登录 登录时间为"+ TimeUtils.timeFormat(LocalDateTime.now()),60*60*10);
        }else if (ObjectUtil.equal(oauthEndpoint,"user")){
             redisService.hSet(RedisConstant.USER_ONLINE_NUMBER,"user_"+number,TimeUtils.timeFormat(LocalDateTime.now()));
             redisService.lrPush(RedisConstant.ADMIN_PROJECT_DYNAMIC_EVALUATION,
                     number+":登录 登录时间为"+ TimeUtils.timeFormat(LocalDateTime.now()),60*60*10);
        }
        return CommonResult.success(accessToken);
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        tokenEndpoint.afterPropertiesSet();
    }

}